﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using Tfs.OnTheRoad.ViewModel;
namespace Tfs.OnTheRoad.Helpers
{
    /// <summary>
    /// Class that Helps to Save and Load Access Profile Settings
    /// </summary>
    public static class SettingsStorageHelper
    {
        public static void ClearSettings(string fileName)
        {
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Check if file exits
                if (isf.FileExists(fileName))
                {
                    isf.DeleteFile(fileName);
                }
            }
        }

        public static XElement SaveSettingViewModel(SettingsViewModel viewModel)
        {
            XElement settingsNode = new XElement("Settings",
                                          new XElement("ProfileName", viewModel.ProfileName),
                                          new XElement("IsDefault", viewModel.IsDefault),
                                          new XElement("Domain", viewModel.Domain),
                                          new XElement("UserName", viewModel.UserName),
                                          new XElement("Password", CryptographyHelper.Encrypt(viewModel.Password)),
                                          new XElement("EndPoint", viewModel.TfsOdataEndPoint),
                                          new XElement("Collection", viewModel.ProjectCollection));
            return settingsNode;
        }

        public static void ReadSettingViewModel(XElement settingsElement, SettingsViewModel viewModelToSet)
        {
            viewModelToSet.ProfileName = settingsElement.Element("ProfileName").Value.Trim();
            viewModelToSet.IsDefault = System.Convert.ToBoolean(settingsElement.Element("IsDefault").Value.Trim());
            viewModelToSet.TfsOdataEndPoint = settingsElement.Element("EndPoint").Value.Trim();
            viewModelToSet.ProjectCollection = settingsElement.Element("Collection").Value.Trim();
            viewModelToSet.Domain = settingsElement.Element("Domain").Value.Trim();
            viewModelToSet.UserName = settingsElement.Element("UserName").Value.Trim();
            viewModelToSet.Password = CryptographyHelper.Decrypt(settingsElement.Element("Password").Value.Trim());
        }

        public static void SaveSettings(ObservableCollection<SettingsViewModel> viewModels, string fileName)
        {
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument settingsDocument = new XDocument();
                XElement rootElement = new XElement("SettingsCollection");
                foreach (SettingsViewModel viewModel in viewModels)
                {
                    XElement settingsNode = SaveSettingViewModel(viewModel);
                    rootElement.Add(settingsNode);
                }
                settingsDocument.Add(rootElement);
                using (Stream file = isf.OpenFile(fileName, FileMode.OpenOrCreate))
                {
                    settingsDocument.Save(file);
                    file.Close();
                }
            }
        }

        public static ObservableCollection<SettingsViewModel> ReadSettings(string fileName)
        {
            ObservableCollection<SettingsViewModel> toReturn = new ObservableCollection<SettingsViewModel>();
            // Try to load previously saved data from IsolatedStorage
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // check if file exits
                if (isf.FileExists(fileName))
                {
                    try
                    {
                        using(Stream file = isf.OpenFile(fileName,FileMode.Open))
                        {
                            XDocument settingsDocument = XDocument.Load(file);
                            IEnumerable<XElement> loadedSettings = settingsDocument.Elements("SettingsCollection").Elements("Settings");
                            foreach (var settingsTag in loadedSettings)
                            {
                                SettingsViewModel loadedItem = new SettingsViewModel();
                                ReadSettingViewModel(settingsTag, loadedItem);
                                toReturn.Add(loadedItem);
                            }
                            file.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show("Not all settings loaded successfully.\n"+ex.Message, "Error loading", System.Windows.MessageBoxButton.OK);
                    }
                }
                return toReturn;
            }
        }
    }
}
